package com.dexilaonian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.dexilaonian.R;
import com.dexilaonian.adpter.MangerAddressAdapter;
import com.dexilaonian.bean.MangerAddressBean;
import com.dexilaonian.bean.PspecBean;
import com.dexilaonian.bean.PspecBean2;
import com.dexilaonian.ui.BaseActivity;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.JsonUtil;
import com.dexilaonian.utils.Logutil;
import com.dexilaonian.utils.Okhttp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class MangerAddressActivity extends BaseActivity {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.base_title_service)
    TextView baseTitleService;
    @Bind(R.id.manger_recycler)
    RecyclerView mangerRecycler;
    @Bind(R.id.btn_new_address)
    Button btnNewAddress;
    private List<MangerAddressBean> mangerList = new ArrayList<>();
    private List<PspecBean> list = new ArrayList<>();
    private String pspec;
    private int productId;
    private int quantity;
    private String shippingAddressId;
    private String confirms;
    private com.alibaba.fastjson.JSONObject json;
    private ArrayList<PspecBean2> serInfo;
    private JSONArray jsonArray2 = new JSONArray();
    @Override
    public int getLayoutID() {
        return R.layout.activity_manger_address;
    }

    @Override
    public void initView() {
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();
        if (intent != null) {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                confirms = extras.getString("CONFIRMS");
                if ("CONFIRMS".equals(confirms)) {
                    json = new com.alibaba.fastjson.JSONObject();
                    pspec = extras.getString("pspec");
                    productId = extras.getInt("productId");
                    quantity = extras.getInt("quantity");
                    json.put("pspec", pspec);
                    json.put("quantity", quantity);
                    json.put("productId", productId);
                    PspecBean pspecBean = new PspecBean();
                    pspecBean.setPspec(pspec);
                    pspecBean.setProductId(productId);
                    pspecBean.setQuantity(quantity);
                    list.add(pspecBean);
                    jsonArray2.add(json);
                } else {
                    serInfo = (ArrayList<PspecBean2>) intent.getSerializableExtra("PSPS");
                }
            }
        }
        Log.e("TTTTTserInfo", serInfo+"="+confirms);
        baseTitleService.setText("管理收货地址");
        initMorenAddress();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);


    }

    //获取默认地址
    private void initMorenAddress() {
        String moren_url = Constant.base_url + "/shipping/default.do";
        Map<String, String> moren_map = new HashMap<>();
        Okhttp.postString(true, moren_url, moren_map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showToast(state);
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject object = new JSONObject(response);
                    int status = Integer.parseInt(object.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(MangerAddressActivity.this, LoginActivity.class));
                        return;
                    }
                    if (status == 0) {
                        String data = object.optString("data");
                        JSONObject jsonObject = new JSONObject(data);
                        shippingAddressId = jsonObject.optString("id");
                        initGetaddress(shippingAddressId);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showToast(state);
            }
        });
    }

    //获取地址列表
    private void initGetaddress(final String shippingAddressId) {
        showProgressBar(true);
        String address_url = Constant.base_url + "/shipping/list.do";
        Map<String, String> address_map = new HashMap<>();
        address_map.put("page", 1 + "");
        address_map.put("limit", 10 + "");
        Okhttp.postString(true, address_url, address_map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
                showToast(state);
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                Logutil.e("TTTnewadd", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 16 || status == 34) {
                        startActivity(new Intent(MangerAddressActivity.this, LoginActivity.class));
                        finish();
                    }
                    if (status == 0) {
                        String data = jsonObject.optString("data");
                        JSONObject object = new JSONObject(data);
                        String items = object.optString("items");
                        final ArrayList<MangerAddressBean> mangerAddressBeen = JsonUtil.json2beans(items, MangerAddressBean.class);
                        mangerList.addAll(mangerAddressBeen);
                        LinearLayoutManager layoutmanager = new LinearLayoutManager(MangerAddressActivity.this);
                        //设置RecyclerView 布局
                        mangerRecycler.setLayoutManager(layoutmanager);
                        Log.e("TTTTshippinlist", mangerList+"="+list);
                        final MangerAddressAdapter mangerAdapter = new MangerAddressAdapter(MangerAddressActivity.this, mangerList,list,confirms,serInfo);
                        for (int i = 0; i < mangerAddressBeen.size(); i++) {
                            String id1 = mangerAddressBeen.get(i).getId();
                            if (shippingAddressId.equals(id1)) {
                                Log.e("TTTTshippingAddressId", MangerAddressActivity.this.shippingAddressId + "====" + id1);
                                mangerAdapter.setChacePosition(i);
                                mangerAdapter.notifyDataSetChanged();
                            }
                        }
                        mangerRecycler.setAdapter(mangerAdapter);
                        mangerAdapter.notifyDataSetChanged();
                        mangerAdapter.setItemClickListener(new MangerAddressAdapter.MyItemClickListener() {
                            @Override
                            public void onItemClick(View view, int position) {
                                showProgressBar(true);
                                mangerAdapter.setChacePosition(position);
                                mangerAdapter.notifyDataSetChanged();
                                String id2 = mangerAddressBeen.get(position).getId();
                                String Shezhi_url = Constant.base_url + "/shipping/setDefault.do";
                                Map<String, String> shezhi_map = new HashMap<String, String>();
                                shezhi_map.put("addressId", id2);
                                Okhttp.postString(true, Shezhi_url, shezhi_map, new Okhttp.CallBac() {
                                    @Override
                                    public void onError(Call call, Exception e, String state, int id) {
                                        showToast(state);
                                        showProgressBar(false);
                                    }

                                    @Override
                                    public void onResponse(String response, int id) {
                                        showProgressBar(false);
                                        try {
                                            JSONObject object1 = new JSONObject(response);
                                            int status1 = Integer.parseInt(object1.optString("status"));
                                            Log.e("TTTSTATUS1", status1 + "===" + response);
                                            if (status1 == 0) {
                                                Log.e("TTTSTATUS22", pspec + "===" + serInfo);

                                                if (!TextUtils.isEmpty(pspec)||serInfo!=null||serInfo.size()!=0) {
                                                    Intent intent = new Intent(MangerAddressActivity.this, ConfirmStoreActivity.class);
                                                    if (confirms.equals("CONFIRMS")) {
                                                        intent.putExtra("productId", productId);
                                                        intent.putExtra("quantity", quantity);
                                                        intent.putExtra("pspec", pspec);
                                                        intent.putExtra("CONFIRMS", "CONFIRMS");
                                                    } else {
                                                        Bundle bundle = new Bundle();
                                                        bundle.putSerializable("PSPS",serInfo);
                                                        intent.putExtras(bundle);
                                                        intent.putExtra("CONFIRMS", "CONFIRMS1");
                                                    }
                                                    startActivity(intent);
                                                    finish();
                                                }
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onNoNetwork(String state) {
                                        showToast(state);
                                        showProgressBar(false);
                                    }
                                });
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
                showToast(state);
            }
        });
    }

    @OnClick({R.id.back, R.id.btn_new_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.btn_new_address:
                Intent intent = new Intent(MangerAddressActivity.this, NewAddressActivity.class);
                intent.putExtra("NUM", "MM");
                if (confirms.equals("CONFIRMS")) {
                    intent.putExtra("productId", productId);
                    intent.putExtra("quantity", quantity);
                    intent.putExtra("pspec", pspec);
                    intent.putExtra("CONFIRMS", "CONFIRMS");
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("PSPS",serInfo);
                    intent.putExtras(bundle);
                    intent.putExtra("CONFIRMS", "CONFIRMS1");
                }
                startActivity(intent);
                finish();
                break;
        }
    }
}
